package com.shiwaixiangcun.customer.module.ticket

import android.annotation.SuppressLint
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.widget.Toast
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import com.shiwaixiangcun.customer.GlobalApi
import com.shiwaixiangcun.customer.GlobalConfig
import com.shiwaixiangcun.customer.R
import com.shiwaixiangcun.customer.base.BaseActivity
import com.shiwaixiangcun.customer.entity.BuyTicketSuccess
import com.shiwaixiangcun.customer.entity.CommonObjCallBack
import com.shiwaixiangcun.customer.entity.SiteDetail
import com.shiwaixiangcun.customer.entity.TicketDetail
import com.shiwaixiangcun.customer.event.EventUtil
import com.shiwaixiangcun.customer.event.SimpleEvent
import com.shiwaixiangcun.customer.network.StringDialogCallBack
import com.shiwaixiangcun.customer.pay.PayUtil
import com.shiwaixiangcun.customer.ui.activity.LoginActivity
import com.shiwaixiangcun.customer.ui.dialog.DialogInfo
import com.shiwaixiangcun.customer.ui.dialog.DialogPay
import com.shiwaixiangcun.customer.utils.*
import kotlinx.android.synthetic.main.activity_ticket.*
import kotlinx.android.synthetic.main.activity_ticket_buy.*
import kotlinx.android.synthetic.main.layout_ticket_buy.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


/**
 * 购买车票页面
 */
class TicketBuyActivity : BaseActivity() {

    /**
     *
     */
    private val ADD_AMOUNT: Int = 1
    private val REDUCE_AMOUNT = 2
    private val UPDATE_UI: Int = 3
    private var siteInfoList: MutableList<SiteDetail>? = null

    /**
     * 车票购买成功后的number号码(用于支付)
     */
    private var ticketNumber: String? = null
    private var scheduleRecordId: Long = 0
    private var midWayId: Long = 0
    var strToken: String? = null
    private var mTicketAmount: Int = 1
    private var mTicketTotal: Int = 1
    var totalPrice: Double = 0.00
    private var unitPrice: Float = 0.00F
    private var mDialogPay: DialogPay? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_ticket_buy)

        EventUtil.getInstance().register(this)
        //初始化Bundle传过来的数据
        val bundle = intent.extras
        midWayId = bundle.getLong("midWayId")
        scheduleRecordId = bundle.getLong("scheduleRecordId")
        strToken = AppSharePreferenceMgr.get(mContext, GlobalConfig.TOKEN, "") as String?
        mDialogPay = DialogPay(mContext)
        initView()
        initData()
    }

    private fun initView() {

        tv_page_name.text = "车票信息"
        siteInfoList = ArrayList()
        back_left?.setOnClickListener { finish() }
        btn_buy?.setOnClickListener {
            if (LoginHelper.isLogin(mContext)) {
                when {
                    TextUtils.isEmpty(edt_user_name.text.toString()) -> showToastShort("你还没有留下你的大名哦")
                    TextUtils.isEmpty(edt_user_phone.text.toString()) -> showToastShort("请输入购票人联系号码")
                    !StringUtil.isPhoneLegal(edt_user_phone.text.toString()) -> showToastShort("请输入合法的手机号码")
                    else -> postTicketInfo(edt_user_name.text.toString(), edt_user_phone.text.toString())
                }
            } else {
                readyGo(LoginActivity::class.java)

            }

        }

        layout_site.setOnClickListener {


            if (siteInfoList?.size == 0) {
                showToastShort("暂无图片信息")
            } else {
                val bundle = Bundle()
                bundle.putParcelableArrayList("siteInfo", siteInfoList as ArrayList<SiteDetail>)
                readyGo(SiteInfoActivity::class.java, bundle)
            }
        }
        iv_add.setOnClickListener {
            EventUtil.getInstance().post(SimpleEvent(SimpleEvent.UPDATE_TICKET_DETAIL, ADD_AMOUNT))

        }
        iv_reduce.setOnClickListener {
            EventUtil.getInstance().post(SimpleEvent(SimpleEvent.UPDATE_TICKET_DETAIL, REDUCE_AMOUNT))

        }
    }

    /**
     * 提交用户购买信息
     */
    private fun postTicketInfo(name: String, phone: String?) {

        OkGo.get<String>(GlobalApi.buyTicket)
                .params("access_token", strToken)
                .params("buyer", name)
                .params("count", mTicketAmount)
                .params("midWayId", midWayId)
                .params("phone", phone)
                .params("scheduleRecordId", scheduleRecordId)
                .execute(object : StringCallback() {
                    override fun onSuccess(response: Response<String>?) {
                        Log.e(BUG_TAG, response?.body().toString())

                        val type = object : TypeToken<CommonObjCallBack<BuyTicketSuccess>>() {}.type
                        val responseEntity = Gson().fromJson<CommonObjCallBack<BuyTicketSuccess>>(response?.body(), type)
                        when (responseEntity.responseCode) {
                            1001 -> {

                                EventUtil.getInstance().post(SimpleEvent(SimpleEvent.BUY_TICKET_SUCCESS, UPDATE_UI, responseEntity.data.number))


                            }
                            else -> {
                                showToastShort("购买车票失败  " + responseEntity.message)
                            }
                        }
                    }

                })
    }


    /**
     * 显示支付对话框
     */
    private fun showPayDialog(ticketNumber: String?) {
        mDialogPay?.setPrice("¥" + ArithmeticUtils.format(totalPrice))
        mDialogPay?.show()
        mDialogPay?.setListener(object : DialogPay.onCallBackListener {
            override fun closeBtn(dialog: DialogPay) {
                dialog.dismiss()
                showNoticeDialog(ticketNumber.toString(), "¥" + ArithmeticUtils.format(totalPrice))
            }

            override fun confirmBtn(dialog: DialogPay) {
                val defaultPay = dialog.defaultPay
                when (defaultPay) {
                    1 -> {
                        Toast.makeText(mContext, "正在进行微信支付", Toast.LENGTH_SHORT).show()
                        strToken?.let { PayUtil.payWeixin(GlobalApi.payWeiXinTicket, ticketNumber!!, it, this@TicketBuyActivity) }
                    }
                    2 -> strToken?.let { PayUtil.payAli(GlobalApi.payZhiFuBaoTicket, ticketNumber!!, it, this@TicketBuyActivity) }
                    else -> {
                        Toast.makeText(mContext, "请选择一种支付方式", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        })
    }

    override fun onDestroy() {
        EventUtil.getInstance().unregister(this)
        super.onDestroy()
    }


    /**
     * 初始化车票信息数据
     */
    private fun initData() {


        OkGo.get<String>(GlobalApi.ticketDetail)
                .params("midWayId", midWayId)
                .params("scheduleRecordId", scheduleRecordId)
                .execute(object : StringDialogCallBack(this) {
                    override fun onSuccess(response: Response<String>?) {

                        val type = object : TypeToken<CommonObjCallBack<TicketDetail>>() {}.type
                        val responseEntity = Gson().fromJson<CommonObjCallBack<TicketDetail>>(response?.body(), type)
                        when (responseEntity.responseCode) {
                            1001 -> {
                                EventUtil.getInstance().post(SimpleEvent(SimpleEvent.UPDATE_TICKET_DETAIL, UPDATE_UI, responseEntity.data))
                            }
                            1016 -> {
                            }
                            else -> {
                                showToastShort("获取数据失败")
                            }

                        }

                    }

                })
    }


    @SuppressLint("SetTextI18n")
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun updateUI(simpleEvent: SimpleEvent) {
        when (simpleEvent.mEventType) {

            SimpleEvent.UPDATE_TICKET_DETAIL -> {


                when (simpleEvent.mEventValue) {
                    UPDATE_UI -> {
                        val ticketDetail = simpleEvent.data as TicketDetail
                        totalPrice = ticketDetail.price.toDouble()
                        mTicketTotal = ticketDetail.remainTicket
                        unitPrice = ticketDetail.price
                        tv_total_price.text = "￥${ticketDetail.price}"
                        tv_passenger_phone.text = "￥${ticketDetail.price}"
                        tv_start.text = ticketDetail.startSite
                        tv_end.text = ticketDetail.endSite
                        tv_ticket_info.text = ticketDetail.survey
                        tv_origin.text = ticketDetail.startLocation
                        tv_destination.text = ticketDetail.endLocation
                        tv_residual_number.text = "剩余${ticketDetail.remainTicket}张"
                        tv_start_time.text = DateUtil.getCustomFormat(ticketDetail.rideTime, "yyyy-MM-dd  HH:mm")

                        ticketDetail.startSiteImages.map {
                            val siteInfo = SiteDetail("上车地址", it.path, it.address)
                            siteInfoList!!.add(siteInfo)
                        }
                        ticketDetail.endSiteImages.map {
                            val siteInfo = SiteDetail("下车地址", it.path, it.address)
                            siteInfoList!!.add(siteInfo)
                        }
                    }
                    ADD_AMOUNT -> {
                        if (mTicketAmount >= mTicketTotal) {
                            showToastShort("请确认你需要购买的车票数目")
                        } else {
                            mTicketAmount++
                            tv_ticket_amount.text = "" + mTicketAmount
                            totalPrice = ArithmeticUtils.mul(mTicketAmount.toDouble(), unitPrice.toDouble(), 2)
                            tv_total_price.text = "￥" + totalPrice
                        }

                    }
                    REDUCE_AMOUNT -> {
                        if (mTicketAmount <= 1) {
                            showToastShort("至少需要买一张票")
                        } else {
                            mTicketAmount--
                            tv_ticket_amount.text = mTicketAmount.toString()
                            totalPrice = ArithmeticUtils.mul(mTicketAmount.toDouble(), unitPrice.toDouble(), 2)
                            tv_total_price.text = "￥${totalPrice}"
                        }
                    }
                }
            }
            SimpleEvent.PAY_SUCCESS -> {
                Log.e(BUG_TAG, "支付成功")
                mDialogPay?.dismiss()
                showToastShort("支付成功")
                val bundle = Bundle()
                bundle.putString("ticketOrderId", "")
                bundle.putString("ticketStatus", "")
                bundle.putString("number", ticketNumber)
                bundle.putBoolean("fromItem", false)
                readyGoThenKill(TicketDetailActivity::class.java, bundle)

            }
            SimpleEvent.PAY_FAIL -> {
                showToastShort("支付失败")
                mDialogPay?.dismiss()


            }
            SimpleEvent.BUY_TICKET_SUCCESS -> {
                ticketNumber = simpleEvent.data as String

                showPayDialog(ticketNumber)
            }
        }


    }


    /**
     *
     */
    private fun showNoticeDialog(number: String, notice: String) {

        val noticeDialog = DialogInfo(this)
        noticeDialog.setDialogTitle("等待支付")
        noticeDialog.setTvConfirm("去支付")
        noticeDialog.setDialogInfo("你购买的车票需要支付$notice,\n支付尚未成功,请重新支付")
        noticeDialog.listener = object : DialogInfo.onCallBackListener {
            override fun closeBtn(dialog: DialogInfo) {
                dialog.dismiss()
            }

            override fun confirmBtn(dialog: DialogInfo) {
                showPayDialog(number)
                dialog.dismiss()
            }
        }
        noticeDialog.show()

    }
}


